<?php
namespace PixelYourSite;
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}
/*
 * @see https://github.com/facebook/facebook-php-business-sdk
 * This class use for sending facebook server events
 */
require_once PYS_PATH . '/modules/facebook/facebook-server-async-task.php';
use PYS_PRO_GLOBAL\FacebookAds\Api;
use PYS_PRO_GLOBAL\FacebookAds\Http\Exception\RequestException;
use PYS_PRO_GLOBAL\FacebookAds\Object\ServerSide\EventRequest;


class FacebookServer {

    private static $_instance;
    private $isEnabled;
    private $hours = ['00-01', '01-02', '02-03', '03-04', '04-05', '05-06', '06-07', '07-08',
        '08-09', '09-10', '10-11', '11-12', '12-13', '13-14', '14-15', '15-16', '16-17',
        '17-18', '18-19', '19-20', '20-21', '21-22', '22-23', '23-24'
    ];
    private $access_token;
    private $testCode;
    private $isDebug;

    public static function instance() {

        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }

        return self::$_instance;

    }


    public function __construct() {
        add_action('init', array($this, 'init'));
    }

    public function init()
    {
        $this->isEnabled = Facebook()->isServerApiEnabled();
        $this->isDebug = PYS()->getOption( 'debug_enabled' );

        if($this->isEnabled) {
            // Classic hook for checkout page
            add_action( 'woocommerce_checkout_update_order_meta', array( $this, 'saveFbTagsInOrder' ), 10, 1 );
            // Hook for Store API (passes WC_Order object instead of order_id)
            add_action( 'woocommerce_store_api_checkout_update_order_meta', array( $this, 'saveFbTagsInOrder' ), 10, 1 );

            // AJAX handlers for fallback
            add_action( 'wp_ajax_pys_api_event',array($this,"catchAjaxEvent"));
            add_action( 'wp_ajax_nopriv_pys_api_event', array($this,"catchAjaxEvent"));
            add_action( 'woocommerce_remove_cart_item', array($this, 'trackRemoveFromCartEvent'), 10, 2);
            //add_action( 'woocommerce_add_to_cart', array($this, 'trackAddToCartEvent'), 40, 4);

            // initialize the s2s event async task (only if queue is disabled)
            if (!PYS()->getOption('queue_enabled', true)) {
                new FacebookAsyncTask();
            }
        }
    }

    public function saveFbTagsInOrder($order_param) {
        $pysData = [];
        $pysData['fbc'] = ServerEventHelper::getFbc();
        $pysData['fbp'] = ServerEventHelper::getFbp();

        // Determine whether the WC_Order object or order ID is passed
        if ( $order_param instanceof WC_Order ) {
            // If the order object is transferred
            $order = $order_param;
        } else {
            // If order_id is passed
            $order = wc_get_order( $order_param );
        }

        if (isWooCommerceVersionGte('3.0.0') && !empty($order)) {
            // WooCommerce >= 3.0
            $order->update_meta_data("pys_fb_cookie", $pysData);
            $order->save();
        } elseif ( ! empty( $order_param ) ) {
            // WooCommerce < 3.0
            update_post_meta($order_param, 'pys_fb_cookie', $pysData);
        }

    }

    /**
     * Send event in shutdown hook (not work in ajax)
     * @param SingleEvent[] $events`
     */
    public function sendEventsAsync($events) {
        // Проверяем, включена ли система очередей
        if (PYS()->getOption('queue_enabled', true)) {
            $this->sendEventsToQueue($events);
            return;
        }

        // Старый способ через асинхронные задачи
        $serverEvents = [];
        foreach ($events as $event) {
            if ($this->isEventDisabledByFilter($event)) {
                continue; // Skip this event, not return (to process other events)
            }
            $ids = $event->payload['pixelIds'];
            $serverEvents[] = [
                "pixelIds" => $ids,
                "event" => ServerEventHelper::mapEventToServerEvent($event)
            ];
        }

        if(count($serverEvents) > 0) {
            do_action('pys_send_server_event', $serverEvents);
        }
    }

    /**
     * Отправка событий в очередь
     * @param SingleEvent[] $events
     */
    private function sendEventsToQueue($events) {
        $serverEvents = [];
        foreach ($events as $event) {

            if ($this->isEventDisabledByFilter($event)) {
                continue; // Skip this event, not return (to process other events)
            }

            $ids = $event->payload['pixelIds'];
            $serverEvents[] = [
                "pixelIds" => $ids,
                "event" => ServerEventHelper::mapEventToServerEvent($event)
            ];
        }

        if(count($serverEvents) > 0) {
            EventsQueue()->addEvent('facebook', $serverEvents);
        }
    }

    /**
     * Send Event Now
     *
     * @param SingleEvent[] $events
     */
    public function sendEventsNow($events) {

        foreach ($events as $event) {

            /**
             * Allows developers to conditionally prevent sending server events.
             *
             * This filter is called before sending any server-side event to Facebook CAPI.
             * Use this to prevent tracking of events from specific sources (e.g., imported orders, API-created orders).
             *
             * @since 9.3.8
             *
             * @param bool        $disable     Whether to disable the event (default: false). Return true to block the event.
             * @param string      $event_name  The event name, e.g. 'Purchase', 'ViewContent', 'AddToCart', etc.
             * @param string      $tag_slug    The platform slug, e.g. 'facebook', 'tiktok', 'pinterest', 'ga4'.
             * @param int|null    $order_id    The order ID if available, or null for non-order events.
             *
             */

            if ($this->isEventDisabledByFilter($event)) {
                continue; // Skip this event, not return (to process other events)
            }
            $serverEvent = ServerEventHelper::mapEventToServerEvent($event);
            $ids = $event->payload['pixelIds'];

            $this->sendEvent($ids,$serverEvent);
        }
    }




    function trackAddToCartEvent($cart_item_key, $product_id, $quantity, $variation_id) {
        if(EventsWoo()->isReadyForFire("woo_add_to_cart_on_button_click")
            && PYS()->getOption('woo_add_to_cart_catch_method') == "add_cart_js") // it ok. We send server method after js, and take event id from cookies
        {
            PYS()->getLog()->debug('trackAddToCartEvent send fb server without browser event');
            if( !empty($variation_id)
                && $variation_id > 0
                && ( !Facebook()->getOption( 'woo_variable_as_simple' )
                    || ( Facebook()->getSlug() == "facebook"
                        && !Facebook\Helpers\isDefaultWooContentIdLogic()
                    )
                )
            ) {
                $_product_id = $variation_id;
            } else {
                $_product_id = $product_id;
            }

            $event =  new SingleEvent("woo_add_to_cart_on_button_click",EventTypes::$DYNAMIC,'woo');
            $event->args = ['productId' => $_product_id,'quantity' => $quantity];
            add_filter('pys_conditional_post_id', function($id) use ($product_id) { return $product_id; });
            $events = Facebook()->generateEvents($event);
            remove_all_filters('pys_conditional_post_id');

            foreach ($events as $singleEvent) {

                if(isset($_COOKIE['pys_landing_page']))
                    $singleEvent->addParams(['landing_page'=> sanitize_url($_COOKIE['pys_landing_page'])]);

                if(isset($_COOKIE["pys_fb_event_id"])) {
                    $singleEvent->payload['eventID'] = json_decode(stripslashes(sanitize_text_field($_COOKIE["pys_fb_event_id"])))->AddToCart;
                }
            }

            $this->sendEventsAsync($events);
        }

    }

    /**
     * @param String $cart_item_key
     * @param \WC_Cart $cart
     */

    function trackRemoveFromCartEvent ($cart_item_key,$cart) {
        $eventId = 'woo_remove_from_cart';

        $url = $_SERVER['HTTP_HOST'].strtok($_SERVER["REQUEST_URI"], '?');
        $postId = url_to_postid($url);
        $cart_id = wc_get_page_id( 'cart' );
        $item = $cart->get_cart_item($cart_item_key);

        if(isset($item['variation_id'])) {
            $product_id = $item['variation_id'];
        } else {
            $product_id = $item['product_id'];
        }


        if(PYS()->getOption( 'woo_remove_from_cart_enabled') && $cart_id==$postId) {
            PYS()->getLog()->debug('trackRemoveFromCartEvent send fb server with out browser event');
            $event = new SingleEvent("woo_remove_from_cart",EventTypes::$STATIC,'woo');
            $event->args=['item'=>$item];

            $events = Facebook()->generateEvents($event);

            foreach ($events as $singleEvent) {
                $singleEvent->addParams(getStandardParams());
                if(isset($_COOKIE['pys_landing_page'])){
                    $singleEvent->addParams(['landing_page'=> sanitize_url($_COOKIE['pys_landing_page'])]);
                }
                if(isset($_COOKIE["pys_fb_event_id"])) {
                    $singleEvent->payload['eventID'] = json_decode(stripslashes(sanitize_text_field($_COOKIE["pys_fb_event_id"])))->RemoveFromCart;
                }

            }

            $this->sendEventsAsync($events);
        }
    }

    /*
     * If server message is blocked by gprg or it dynamic
     * we send data by ajax request from js and send the same data like browser event
     */
    function catchAjaxEvent() {
        PYS()->getLog()->debug('catchAjaxEvent send fb server from ajax');
        $event = sanitize_text_field($_POST['event']);
        $eventSlug = sanitize_text_field($_POST['event_slug']);
        $data = isset($_POST['data']) ? $_POST['data'] : array();
        $ids = $_POST['ids'];
        $eventID = sanitize_text_field($_POST['eventID']);
        $wooOrder = isset($_POST['woo_order']) && is_numeric($_POST['woo_order']) ? (int) $_POST['woo_order'] : null;
        $eddOrder = isset($_POST['edd_order']) && is_numeric($_POST['edd_order']) ? (int) $_POST['edd_order'] : null;

        if ( empty( $_REQUEST['ajax_event'] ) || !wp_verify_nonce( $_REQUEST['ajax_event'], 'ajax-event-nonce' ) ) {
            wp_die();
            return;
        }

       if($event == "hCR") $event="CompleteRegistration"; // de mask completer registration event if it was hidden

        $singleEvent = $this->dataToSingleEvent($event,$data,$eventID,$ids,$wooOrder,$eddOrder,$eventSlug);

        $this->sendEventsNow([$singleEvent]);

        wp_die();
    }

    /**
     * @param $eventName
     * @param $params
     * @param $eventID
     * @param $ids
     * @param $wooOrder
     * @param $eddOrder
     * @return SingleEvent
     */
    private function dataToSingleEvent($eventName,$params,$eventID,$ids,$wooOrder,$eddOrder,$eventSlug = "") {
        $singleEvent = new SingleEvent($eventSlug,"");

        $payload = [
            'name' => $eventName,
            'eventID'   => $eventID,
            'woo_order' => $wooOrder,
            'edd_order' => $eddOrder,
            'pixelIds'  => $ids
        ];
        $singleEvent->addParams($params);
        $singleEvent->addPayload($payload);

        return $singleEvent;
    }



    /**
     * Send event for each pixel id
     * @param array $pixel_Ids //array of facebook ids
     * @param $event //One Facebook event object
     */
    function sendEvent($pixel_Ids, $event) {

        if (!$event) {
            return;
        }

        if(!$this->access_token) {
            $this->access_token = Facebook()->getApiTokens();
            $this->testCode = Facebook()->getApiTestCode();
        }

	    $event_id = $event->getEventId();
	    foreach($pixel_Ids  as $pixel_Id) {

		    if(empty($this->access_token[$pixel_Id])) continue;

		    if(!empty($event->getEventId())) {
			    $event->setEventId($event_id);
		    }


            /**
             * filter pys_before_send_fb_server_event
             * Help add custom options or get data from event before send
             * FacebookAds\Object\ServerSide\Event $event
             * String $pixel_Id
             * String EventId
             */

            try{

                $api = Api::init(null, null, $this->access_token[$pixel_Id],false);
                $opts = $api->getHttpClient()->getAdapter()->getOpts();
                if ($opts instanceof \ArrayObject && $opts->offsetExists(CURLOPT_CONNECTTIMEOUT)) {
                    $opts->offsetSet(CURLOPT_CONNECTTIMEOUT, 30);
                    $api->getHttpClient()->getAdapter()->setOpts($opts);
                }

                $event = apply_filters("pys_before_send_fb_server_event",$event,$pixel_Id,$event->getEventId());

                $request = (new EventRequest($pixel_Id))->setEvents([$event]);
                $request->setPartnerAgent("dvpixelyoursite");
                if(!empty($this->testCode[$pixel_Id])) {
                    $request->setTestEventCode($this->testCode[$pixel_Id]);
                }
                PYS()->getLog()->debug('Send FB server event',$request);

                $response = $request->execute();
                PYS()->getLog()->debug('Response from FB server',$response);
            } catch (\Exception   $e) {
                if($e instanceof RequestException) {
                    PYS()->getLog()->error('Error send FB server event '.$e->getErrorUserMessage(),$e->getResponse());
                } else {
                    PYS()->getLog()->error('Error send FB server event',$e);
                }
            }
        }
    }

    /**
     * Check if server event should be disabled by filter
     *
     * @param SingleEvent $event The event to check
     * @return bool True if event should be blocked, false otherwise
     */
    private function isEventDisabledByFilter($event) {
        $event_name = $event->getId();
        $woo_order = isset($event->payload['woo_order']) ? $event->payload['woo_order'] : null;
        $edd_order = isset($event->payload['edd_order']) ? $event->payload['edd_order'] : null;
        $order_id = $woo_order ?? $edd_order;

        $is_disabled = apply_filters('pys_disable_server_event_filter', false, $event_name, 'facebook', $order_id);

        if ($is_disabled) {
            PYS()->getLog()->debug('Facebook server event blocked by pys_disable_server_event_filter', [
                'event_name' => $event_name,
                'order_id' => $order_id
            ]);
        }

        return $is_disabled;
    }

}

/**
 * @return FacebookServer
 */
function FacebookServer() {
    return FacebookServer::instance();
}

FacebookServer();





